﻿using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.IO;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using Openfree.Framework.DataAccess;
using Openfree.Framework.Common;
using FreeTextBoxControls;


public partial class Document_DocumentEdit : BaseUserControl
{
    protected string TableName = "T_Document";

    protected void Page_Load(object sender, EventArgs e)
    {
        {
            DocumentCategoryAccess documentCategoryAccess = new DocumentCategoryAccess(base.Connection);
            IList ddlNodesIDList = documentCategoryAccess.LoadListTree();
            for (int i = 0; i <= ddlNodesIDList.Count - 1; i++)
            {
                object[] obj;
                obj = (object[])ddlNodesIDList[i];
                ListItem item = new ListItem(HttpUtility.HtmlDecode((string)obj[1]), (string)obj[0]);
                ddlCategory.Items.Add(item);
            }

            string[] fontList = new string[] {"Arial","Courier   New","Garamond","Georgia","Tahoma",
                "Times   New   Roman","Verdana","宋体","黑体","隶书",
                "楷体_GB2312","幼圆","仿宋_GB2312","方正姚体","方正舒体"};
            Toolbar toolbar = freeTextBox.Toolbars[0];
            FontFacesMenu fontmenu = (FontFacesMenu)toolbar.Items[1];
            foreach (string fontName in fontList)
            {
                fontmenu.Items.Add(new ToolbarListItem(fontName, fontName));
                ddlSubjectFont.Items.Add(fontName);
            }
            for (int i = 1; i < 7; i++)
            {
                ddlSubjectSize.Items.Add(i.ToString());
            }

            InitTempVirtualFolder();
            UploadFile1.SetShowButtonClientID(btnUpload.ClientID);
            UploadFile1.SetMaxFiles(5);
            UploadFile1.SetValidExtensions("jpg,jpeg,gif,png");
            UploadFile1.SetInvalidExtensionMessage("类型错误");
            UploadFile1.SetSubject("上传图片信息");

            hfAddOrEdit.Value = "Add";
            literalCaption.Text = "新建文档";
            if (!string.IsNullOrEmpty(Request["DocumentID"]))
            {
                hfAddOrEdit.Value = "Edit";
                literalCaption.Text = "编辑文档";
                hfID.Value = Request["DocumentID"].Replace("'", string.Empty);
                InitData(Request["DocumentID"]);
            }
        }

        UploadFile1.OnUploadComplete += new Controls_UploadFile_UploadFile.UploadComplete(UploadFile1_OnUploadComplete);
    }

    protected void UploadFile1_OnUploadComplete(UploadCompleteEventArgs e)
    {
        if (!UploadFile1.GetInsertEditer()) return;
        string javascript = string.Empty;
        foreach (DataRow row in e.UploadFile.Rows)
        {
            javascript += "<img src=\'" + SessionManager.UploadURL.Replace("~/", "../") + row["fileName"].ToString() + "\' /><br />";
        }

        string inbox = "<script>function insertHtml() { " +
            "var images = \"" + javascript + "\";" +
            "FTB_API[\"" + freeTextBox.ClientID + "\"].InsertHtml(images);}" +
        "setTimeout('insertHtml()', 1000);</script>";

        //inbox = string.Format(inbox, );
        Page.ClientScript.RegisterStartupScript(this.GetType(), this.ClientID, inbox);
    }

    private string TempVirtualFolder
    {
        get
        {
            return freeTextBox.ImageGalleryPath;
        }
    }

    private void InitTempVirtualFolder()
    {
        string folderName = System.DateTime.Now.ToString("yyMMdd") + "-" + Guid.NewGuid().ToString();
        //Response.Write("SessionManager.TempVirtualFolder" + SessionManager.TempVirtualFolder +"<br/>");                
        freeTextBox.ImageGalleryPath = "~/Temp/" + folderName;
        //更新 UploadFile1 上传文件路径， UploadStreamProvider 能够主动读取
        SessionManager.UploadURL = "~/Temp/" + folderName;
    }

    private void InitData(string documentID)
    {
        DataSet ds = DocumentAccess.GetDataSet(hfID.Value, TableName);
        if (ds != null && ds.Tables[0].Rows.Count > 0)
        {
            DataRow row = ds.Tables[0].Rows[0];
            string imageGalleryPath = StoreLocationAccess.GetResourceURL(row["StoreLocationID"].ToString(),
                System.Convert.ToDateTime(row["CreateDate"].ToString()), documentID);
            //fix 路径不存在,插入图片页面报错
            //   ../ 是为了去掉SiteAdmin路径
            if (!Directory.Exists(Server.MapPath("../" + imageGalleryPath)))
            {
                Directory.CreateDirectory(Server.MapPath("../" + imageGalleryPath));
            }
            freeTextBox.ImageGalleryPath = "../" + imageGalleryPath;
            //更新 UploadFile1 上传文件路径， UploadStreamProvider 能够主动读取
            SessionManager.UploadURL = "~/" + imageGalleryPath;


            ddlCategory.SelectByValue = row["CategoryID"].ToString();
            tbSubject.Text = row["Subject"].ToString();
            tbSubTitle.Text = row["SubTitle"].ToString();
            tbSource.Text = row["Source"].ToString();
            tbAuthor.Text = row["Author"].ToString();
            tbHotImageFileName.Text = row["HotImageFileName"].ToString();
            tbHotImageTip.Text = row["HotImageTip"].ToString();
            ddlSubjectColor.SelectByValue = row["SubjectColor"].ToString();
            ddlSubjectFont.SelectByValue = row["SubjectFont"].ToString();
            ddlSubjectSize.SelectByValue = row["SubjectSize"].ToString();
            cbOnTop.Checked = false;
            if (row["OnTop"].ToString().ToLower() == "true")
            {
                cbOnTop.Checked = true;
            }
            cbRecommended.Checked = false;
            if (row["Recommended"].ToString().ToLower() == "true")
            {
                cbRecommended.Checked = true;
            }
            cbAllowFeedback.Checked = false;
            if (row["AllowFeedback"].ToString().ToLower() == "true")
            {
                cbAllowFeedback.Checked = true;
            }
            cbSubjectBlod.Checked = false;
            if (row["SubjectBold"].ToString().ToLower() == "true")
            {
                cbSubjectBlod.Checked = true;
            }
            OnInitData(ds);

            freeTextBox.Text = row["DocumentContent"].ToString();
            //   ../ 是为了去掉SiteAdmin路径
            //freeTextBox.Text = freeTextBox.Text.Replace("../" + imageGalleryPath,
            //    imageGalleryPath);
            freeTextBox.Text = freeTextBox.Text.Replace(imageGalleryPath,
                "../" + imageGalleryPath);
        }
    }

    protected virtual void OnInitData(DataSet ds)
    {

    }


    protected void btnSave_Click(object sender, EventArgs e)
    {
        SaveData(true);
    }


    protected void btnSaveTemp_Click(object sender, EventArgs e)
    {
        SaveData(false);
    }

    private void SaveData(bool published)
    {
        if (hfAddOrEdit.Value == "Edit")
        {
            string documentID = hfID.Value;
            DocumentCategoryAccess documentCategoryAccess = new DocumentCategoryAccess(base.Connection);
            DataSet ds = DocumentAccess.GetDataSet(documentID, TableName);
            DataRow row = ds.Tables[0].Rows[0];
            string oldLocationID = documentCategoryAccess.GetStoreLocationID(row["CategoryID"].ToString());
            string newLocationID = documentCategoryAccess.GetStoreLocationID(ddlCategory.SelectedValue);
            string oldURL = StoreLocationAccess.GetResourceURL(oldLocationID,
                System.Convert.ToDateTime(row["CreateDate"].ToString()), documentID);
            string newURL = StoreLocationAccess.GetResourceURL(newLocationID,
                System.Convert.ToDateTime(row["CreateDate"].ToString()), documentID);
            //../image/2008/03/05/bd60c1ed-2042-49ac-bc29-06d6824364c8/profile_arrow.jpg
            string htmlCode = freeTextBox.Text.Replace("../" + oldURL, newURL);
            //http://localhost:3489/WebSite/image/2008/03/05/bd60c1ed-2042-49ac-bc29-06d6824364c8/profile_arrow.jpg
            htmlCode = htmlCode.Replace(ApplicationPath + "/" + oldURL, newURL);

            string oldFullPath = StoreLocationAccess.CreateLocalResourceDirectory(oldLocationID, DateTime.Now, documentID);
            string newFullPath = StoreLocationAccess.CreateLocalResourceDirectory(newLocationID, DateTime.Now, documentID);
            if (oldFullPath != newFullPath)
            {
                DirectoryManager.CopyDirectory(oldFullPath, newFullPath);
                DirectoryManager.DeleteDirectory(oldFullPath);
            }
            row["DocumentID"] = documentID;
            row["CategoryID"] = ddlCategory.SelectedValue;
            row["Subject"] = tbSubject.Text.Trim();
            row["SubTitle"] = tbSubTitle.Text.Trim();
            row["Source"] = tbSource.Text.Trim();
            row["Author"] = tbAuthor.Text.Trim();
            row["DocumentContent"] = htmlCode;
            row["Published"] = published;
            row["Recorder"] = SessionManager.LoginName;
            row["OnTop"] = cbOnTop.Checked;
            row["Recommended"] = cbRecommended.Checked;
            row["AllowFeedback"] = cbAllowFeedback.Checked;
            row["StoreLocationID"] = newLocationID;
            row["HotImageFileName"] = string.Empty;
            row["HotImageTip"] = string.Empty;
            row["HasImage"] = false;
            row["SubjectColor"] = ddlSubjectColor.SelectedValue;
            row["SubjectFont"] = ddlSubjectFont.SelectedValue;
            row["SubjectSize"] = ddlSubjectSize.SelectedValue;
            row["SubjectBold"] = cbSubjectBlod.Checked;                

            string[] files = System.IO.Directory.GetFiles(newFullPath);
            foreach (string file in files)
            {
                if (file.ToLower().IndexOf(".gif") > -1 ||
                    file.ToLower().IndexOf(".jpg") > -1 ||
                    file.ToLower().IndexOf(".bmp") > -1 ||
                    file.ToLower().IndexOf(".png") > -1)
                {
                    row["HasImage"] = true;
                }
            }
            if (!string.IsNullOrEmpty(tbHotImageFileName.Text.Trim()))
            {
                row["HotImageFileName"] = tbHotImageFileName.Text.Trim();
                row["HotImageTip"] = tbHotImageTip.Text.Trim();
            }

            BaseAccess.UpdateDataSet(base.Connection, "T_Document", ds);
        }
        else
        {
            // tempURL              /WebSite/Temp/070822-63d51050-ccb7-431c-bdac-4353bb1c90b9
            // documentURL          Document/2007/08/22/7fe74420-533b-42fc-9eb9-b8fd3dd68242
            // documentFullPath     C:\Document\2007\08\22\7fe74420-533b-42fc-9eb9-b8fd3dd68242
            // src Http://localhost:8080/WebSite/....
            // src Document/2007/08/22/7fe74420-533b-42fc-9eb9-b8fd3dd68242/ME3.JPG
            DocumentCategoryAccess documentCategoryAccess = new DocumentCategoryAccess(base.Connection);
            string storeLocationID = documentCategoryAccess.GetStoreLocationID(ddlCategory.SelectedValue);
            string documentID = Guid.NewGuid().ToString();
            string tempURL = ApplicationPath + TempVirtualFolder.Replace("~", string.Empty);
            string documentURL = StoreLocationAccess.GetResourceURL(storeLocationID, DateTime.Now, documentID);
            string documentFullPath = StoreLocationAccess.CreateLocalResourceDirectory(storeLocationID, DateTime.Now, documentID);
            string htmlCode = freeTextBox.Text;
            htmlCode = htmlCode.Replace(tempURL, documentURL);
            htmlCode = htmlCode.Replace(ApplicationPath + "/" + documentURL, documentURL);
            DirectoryManager.CopyDirectory(Server.MapPath(tempURL), documentFullPath);

            DataSet ds = BaseAccess.GetDataSet(base.Connection, "select * from T_Document where 1=2", "T_Document");
            DataRow row = ds.Tables[0].NewRow();
            row["DocumentID"] = documentID;
            row["CategoryID"] = ddlCategory.SelectedValue;
            row["Subject"] = tbSubject.Text.Trim();
            row["SubTitle"] = tbSubTitle.Text.Trim();
            row["CreateDate"] = DateTime.Now.ToString();
            row["Source"] = tbSource.Text.Trim();
            row["Author"] = tbAuthor.Text.Trim();
            row["DocumentContent"] = htmlCode;
            row["Published"] = published;
            row["Recorder"] = SessionManager.LoginName;
            row["OnTop"] = cbOnTop.Checked;
            row["Recommended"] = cbRecommended.Checked;
            row["AllowFeedback"] = cbAllowFeedback.Checked;
            row["StoreLocationID"] = storeLocationID;
            row["HotImageFileName"] = string.Empty;
            row["HotImageTip"] = string.Empty;
            row["HasImage"] = false;
            row["ViewCount"] = 0;
            row["SubjectColor"] = ddlSubjectColor.SelectedValue;
            row["SubjectFont"] = ddlSubjectFont.SelectedValue;
            row["SubjectSize"] = ddlSubjectSize.SelectedValue;
            row["SubjectBold"] = cbSubjectBlod.Checked;
            row["Tag"] = string.Empty;
            

            documentURL = StoreLocationAccess.GetLocalResourceDirectory(storeLocationID, DateTime.Now, documentID);
            string[] files = System.IO.Directory.GetFiles(documentURL);
            foreach (string file in files)
            {
                if (file.ToLower().IndexOf(".gif") > -1 ||
                    file.ToLower().IndexOf(".jpg") > -1 ||
                    file.ToLower().IndexOf(".bmp") > -1 ||
                    file.ToLower().IndexOf(".png") > -1)
                {
                    row["HasImage"] = true;
                }
            }
            if (!string.IsNullOrEmpty(tbHotImageFileName.Text.Trim()))
            {
                row["HotImageFileName"] = tbHotImageFileName.Text.Trim();
                row["HotImageTip"] = tbHotImageTip.Text.Trim();
            }

            ds.Tables[0].Rows.Add(row);
            BaseAccess.UpdateDataSet(base.Connection, "T_Document", ds);
        }

        tbSubject.Text = string.Empty;
        tbSubTitle.Text = string.Empty;
        tbSource.Text = string.Empty;
        tbAuthor.Text = string.Empty;
        freeTextBox.Text = string.Empty;
        tbHotImageFileName.Text = string.Empty;
        tbHotImageTip.Text = string.Empty;
        cbOnTop.Checked = false;
        cbAllowFeedback.Checked = false;
        cbRecommended.Checked = false;
        ddlSubjectColor.SelectedIndex = 0;
        ddlSubjectFont.SelectedIndex = 0;
        ddlSubjectSize.SelectedIndex = 0;
        cbSubjectBlod.Checked = false;

        //if (hfAddOrEdit.Value == "Edit")
        //{
        //    //删除
        //    string result = BaseAccess.ExecuteScalar(base.Connection,
        //        "select CreateDate from T_Document where DocumentID='" + hfID.Value + "'");

        //    result = base.CreateDocumentFolder(Convert.ToDateTime(result), hfID.Value);
        //    DeleteFolder(Server.MapPath(result));

        //    string cmdText = "delete from T_Document where DocumentID='{0}'";
        //    BaseAccess.ExecuteNonQuery(base.Connection,
        //        string.Format(cmdText, hfID.Value));
        //}
        InitTempVirtualFolder();
        //Page.ClientScript.RegisterStartupScript(this.GetType(),
        //       "alert", JavaScript.InBox("FTB_FreeTextBox.prototype.InsertImageFromGallery();\r\n") + JavaScript.Alert("保存成功"));
        base.Alert("保存成功");
    }

    protected void btnClear_Click(object sender, EventArgs e)
    {
        freeTextBox.Text = string.Empty;
    }
}